import axios from 'axios'
import { app } from '@/main'
import { useUserStore } from '@/stores/user'

//const baseUrl = 'http://localhost:5147'
const baseUrl = 'https://api.bmyx.love'

axios.interceptors.request.use((config: any) => {
  config.headers['Authorization'] = 'Bearer ' + sessionStorage.getItem('token')
  return config
})

// 队列来存储需要重试的请求配置  
let retryQueue:any = [];
let isRefreshing = false;
let currentPromise = null;

// 添加请求到重试队列  
function addToRetryQueue(config : any) {
  return new Promise((resolve) => {
    retryQueue.push({ resolve, config });
  });
}

// 从队列中取出请求并重新发起  
function retryQueuedRequests() {
  while (retryQueue.length) {
    const { resolve, config } = retryQueue.shift();
    resolve(axios(config));
  }
}

axios.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    const userStore = useUserStore()// 这个要用在方法里
    if (error.response && error.response.status === 401) {
      if (!isRefreshing) {
        isRefreshing = true;
        // todo：这里使用绝对路径，如果使用相对路径，前缀会带上当前页面路径导致404的错误，还不知道啥原因
        currentPromise = axios.get(baseUrl + '/user/RefreshToken/' + sessionStorage.getItem('refreshtoken')) 
          .then((response) => {
            userStore.userInfo = response.data
            sessionStorage.setItem('token', response.data.accessToken)
            sessionStorage.setItem('refreshtoken', response.data.refreshToken)
            userStore.token = response.data.accessToken
            userStore.refreshToken = response.data.refreshToken
            // 刷新成功后，重新发起队列中的请求  
            retryQueuedRequests();
          })
          .catch((err) => { // todo:这里刷新token返回401时，就进不了这个分支，所以改为返回400
            // token刷新失败的处理逻辑  
            // 清除队列中的请求（或执行其他逻辑）  
            retryQueue = [];
            // 刷新失败，返回首页
            userStore.userInfo = ''
            userStore.token = ''
            userStore.refreshToken = ''
            userStore.accessArticles = []
            sessionStorage.removeItem('token')
            sessionStorage.removeItem('refreshtoken')
          })
          .finally(() => {
            isRefreshing = false;
            currentPromise = null;
          });
      }
      // 将原始失败请求的配置添加到重试队列，并返回一个新的Promise  
      // 当token刷新成功后，这个Promise将被resolve  
      return addToRetryQueue(error.config).then((promise) => {  
        // 标记这个请求为重试请求，避免无限循环  
        //promise.config.__isRetryRequest = true;  
        return promise;  
      });  
    }
    else{
      return Promise.reject(error)
    }
  }
)

// axios.interceptors.response.use(
//   (response) => {
//     switch (response.data.code) {
//       case 50000:
//         app.config.globalProperties.$notify({
//           title: 'Error',
//           message: '系统异常,请联系管理员',
//           type: 'error'
//         })
//         break
//       case 40001:
//         app.config.globalProperties.$notify({
//           title: 'Error',
//           message: '用户未登录',
//           type: 'error'
//         })
//         break
//     }
//     return response
//   },
//   (error) => {
//     return Promise.reject(error)
//   }
// )
export default {
  getTopAndFeaturedArticles: () => {
    return axios.get('/api/articles/topAndFeatured')
  },
  getArticles: (params: any) => {
    return axios.post('/api/articles/all', params)
  },
  getArticlesByCategoryId: (params: any) => {
    return axios.post('/api/articles/categoryId', params)
  },
  getArticeById: (articleId: any) => {
    return axios.get('/api/articles/' + articleId)
  },
  getAllCategories: () => {
    return axios.get('/api/categories/all')
  },
  getAllTags: () => {
    return axios.get('/api/tags/all')
  },
  getTopTenTags: () => {
    return axios.get('/api/tags/topTen')
  },
  getArticlesByTagId: (params: any) => {
    return axios.get('/api/articles/tagId', params)
  },
  getAllArchives: (params: any) => {
    return axios.get('/api/archives/all', params)
  },
  login: (params: any) => {
    return axios.post('/api/user/login', params)
  },
  saveComment: (params: any) => {
    return axios.post('/api/comments/save', params)
  },
  getComments: (params: any) => {
    return axios.post('/api/comments', params)
  },
  getTopSixComments: () => {
    return axios.get('/api/comments/topSix')
  },
  getAbout: () => {
    return axios.get('/api/admin/about')
  },
  getFriendLink: () => {
    return axios.post('/api/links',{})
  },
  submitUserInfo: (params: any) => {
    return axios.post('/api/users/saveuser', params)
  },
  getUserInfoById: (id: any) => {
    return axios.get('/api/users/info/' + id)
  },
  updateUserSubscribe: (params: any) => {
    return axios.post('/api/users/subscribe', params)
  },
  sendValidationCode: (username: any) => {
    return axios.post('/api/user/code', {
        'username' : username
    })
  },
  bindingEmail: (params: any) => {
    return axios.put('/api/users/email', params)
  },
  register: (params: any) => {
    return axios.post('/api/user/register', params)
  },
  searchArticles: (params: any) => {
    return axios.get('/api/articles/search', {
      params: params
    })
  },
  getAlbums: () => {
    return axios.get('/api/photos/albums')
  },
  getPhotosBuAlbumId: (albumId: any, params: any) => {
    return axios.get('/api/albums/' + albumId + '/photos', {
      params: params
    })
  },
  getWebsiteConfig: () => {
    return axios.get('/api/home')
  },
  qqLogin: (params: any) => {
    return axios.post('/api/users/oauth/qq', params)
  },
  report: () => {
    axios.get('/api/report')
  },
  getTalks: (params: any) => {
    return axios.post('/api/talks', {
      params: params
    })
  },
  getTalkById: (id: any) => {
    return axios.get('/api/talks/' + id)
  },
  logout: () => {
    return axios.post('/api/user/logout')
  },
  getRepliesByCommentId: (commentId: any) => {
    return axios.get(`/api/comments/${commentId}/replies`)
  },
  updatePassword: (params: any) => {
    return axios.put('/api/users/password', params)
  },
  accessArticle: (params: any) => {
    return axios.post('/api/articles/access', params)
  }
}
